App.controller('busController', ['$rootScope', '$scope', '$state', 'Page', function($rootScope, $scope, $state, Page) {

    $scope.grid = {
        add : function() {
            $scope.bus = {};
            $scope.modal.show();
        },
        update: function(row) {
            $scope.bus = row;
            $scope.modal.show();
        },
        save : function() {
            $scope.validateForm.doValidate();
            if($scope.validateForm.$valid) {
                Page.ajaxPost($scope.bus.busId ? 'bus/update.do' : 'bus/add.do', $scope.bus, function() {
                    Page.notice("操作成功!");
                    $scope.grid.query();
                    $scope.grid.cancel();
                });
            }
        },
        syncMediaBus : function() {
            Page.ajaxPost('bus/refresh.do', null, function (resp) {
                Page.notice('车辆数据刷新完成!');
                $scope.grid.query();
            });
        },
        move : function(row) {
            //$scope.temp = angular.copy(row);
            //$scope.busHistory = row;
            //$scope.busHistoryModal.show();

            Page.ajaxPost('bus/transQuery.do', {busId : row.busId}, function (resp) {
                var returnData = resp.data;
                $scope.sortTransList(returnData);
                //Page.notice('车辆数据刷新完成!');
                $scope.busTransModal.show();
            });

        },
        viewBusPosition : function(row) {
            $scope.busPositionObj = angular.copy(row);
            $scope.busPositionModal.show();
        },
        adHistory : function(row) {
            Page.ajaxPost('bus/adHistory.do', {busId : row.busId}, function (resp) {
                $scope.historyList = resp.data;
                $scope.adHistoryModal.show();
            });
        },

        column_defs: [{
            target: 1,
            template: function(row){
                return '<a href="javascript:void(0)" ed-click="moveHistory">'+row.vehicleNo+'</a>'
                    + '<a href="javascript:void(0);" ed-click="viewBusPosition" title="定位" class="icon-pointer" style="padding-left: 10px;font-size:13px;"></a>'
            }
        },
            {
                target : 11,
                buttons : [
                    {
                        name: '编辑',
                        class: 'btn-warning btm-sm',
                        icon: 'fa-edit',
                        event: 'update'
                    },
                    {
                        name: '删除',
                        class: 'btn-danger',
                        icon: 'fa-close',
                        event: function(row) {
                            Page.confirm("确定要删除吗？", function() {
                                Page.ajaxPost('bus/delete.do', row, function() {
                                    $scope.grid.query();
                                });
                            });
                        }
                    },
                    {
                        name: '异动',
                        class: 'btn btn-xs purple',
                        icon: 'fa-file-text-o',
                        event: 'move'
                    },
                    {
                        name: '广告历史',
                        class: 'btn btn-xs blue',
                        icon: 'glyphicon glyphicon-tag',
                        event: 'adHistory'
                    }

                ]
            }
        ]
    };

    $scope.sortTransList = function(returnData) {
        var companyInnerTransList = returnData["companyInnerTransList"];
        var companyTransList = returnData["companyTransList"];
        var vehicleUsingList = returnData["vehicleUsingList"];

        var total = angular.extend([],companyInnerTransList,companyTransList,vehicleUsingList);
        //console.log(total);

        total.sort(function(a, b){
            return a < b ? 1 : -1;
        });

        $scope.busTransList = angular.copy(total);
    };

    $scope.moveGrid = {
        options : {
            lazy : true,
            bAutoWidth : false
        }
    };


    $scope.cancelBusTransModal = function() {
        $scope.busTransModal.hide();
    };

    $scope.cancelAdHistoryModal = function() {
        $scope.adHistoryModal.hide();
    };

    $scope.busPositionModal = {
        onShow : function() {
            $scope.busPositionModal.setTitle("车辆定位【" + $scope.busPositionObj.vehicleNo + "】");
            //高德
            var mapDiv = "busPositionModalMapDiv";
            var width = $('#' + mapDiv).width();
            var height = $('#' + mapDiv).height();
            $scope.busPositionObj.map = new AMap.Map(mapDiv, {resizeEnable: true,zoom:13,center: [114.296308, 30.595444]});

            Page.notice("正在定位...");
            Page.ajaxPostQuiet('bus/gps.do', {vehicleNo : $scope.busPositionObj.vehicleNo,lineNo : $scope.busPositionObj.lineNo}, function (resp) {
                if(resp.data && resp.data.gpsdatatime){

                    var po = GPSUtil.GPS.gcj_encrypt(resp.data.latitude*1, resp.data.longitude*1);
                    var infoWindow = new AMap.InfoWindow({
                        content:$scope.busPositionObj.vehicleNo + '【运行线路：' + resp.data.lineName + '】【最后定位时间：' + resp.data.gpsdatatime +'】【方向角：' + resp.data.direction + '】'
                    });
                    var busMarker = new AMap.Marker({
                        position: [po.lon, po.lat],
                        icon: "./assets/admin/img/map_bus_orange.png",
                        map:$scope.busPositionObj.map
                    }).on('click',function(e){
                            infoWindow.open($scope.busPositionObj.map, e.target.getPosition());
                        });
                    infoWindow.open($scope.busPositionObj.map, busMarker.getPosition());
                }
            });

            if($scope.busPositionObj.lineNo){
                AMap.service(["AMap.LineSearch"], function() {
                    var linesearch = new AMap.LineSearch({
                        city:'027',
                        extensions:'all'
                    });
                    linesearch.search($scope.busPositionObj.lineNo, function(status, result) {
                        if (status === 'complete' && result.info === 'OK' && result.lineInfo.length > 0) {
                            var busArr = result.lineInfo[0].path;
                            var stops = result.lineInfo[0].via_stops;
                            var startPot = stops[0].location;
                            var endPot = stops[stops.length - 1].location;

                            new AMap.Marker({
                                map: $scope.busPositionObj.map,
                                position: [startPot.lng, startPot.lat], //基点位置
                                icon: "http://webapi.amap.com/theme/v1.3/markers/n/start.png",
                                zIndex: 10
                            });
                            new AMap.Marker({
                                map: $scope.busPositionObj.map,
                                position: [endPot.lng, endPot.lat], //基点位置
                                icon: "http://webapi.amap.com/theme/v1.3/markers/n/end.png",
                                zIndex: 10
                            });
                            //绘制乘车的路线
                            busPolyline = new AMap.Polyline({
                                map: $scope.busPositionObj.map,
                                path: busArr,
                                strokeColor: "#09f",//线颜色
                                strokeOpacity: 0.8,//线透明度
                                strokeWeight: 5//线宽
                            });
                        }
                    });
                });
            }

            setTimeout(function() {
                $scope.busPositionObj.map.setFitView();
            },300);
        }
    }


}]);